package org.jinxing.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jinxing.dao.BooksCaseDAO;
import org.jinxing.dao.BooksClassfyDAO;
import org.jinxing.dao.BooksInfoDAO;
import org.jinxing.dao.BooksPenaltyDAO;
import org.jinxing.dao.BorrowsInfoDAO;
import org.jinxing.dao.RolesInfoDAO;
import org.jinxing.model.BooksCase;
import org.jinxing.model.BooksClassfy;
import org.jinxing.model.BooksClassfyExample;
import org.jinxing.model.BooksInfo;
import org.jinxing.model.BooksInfoExample;
import org.jinxing.model.BooksPenalty;
import org.jinxing.model.BooksPenaltyExample;
import org.jinxing.model.BorrowsInfo;
import org.jinxing.model.UsersInfo;
import org.jinxing.model.BooksInfoExample.Criteria;
import org.jinxing.model.BorrowsInfoExample;
import org.jinxing.service.UsersInfoService;
import org.jinxing.utils.JsonUtils;
import org.jinxing.utils.ModelUtils;
import org.jinxing.utils.RequestUtils;
import org.jinxing.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 个人中心书籍服务
 * @author jinxing
 *
 */

@Controller
@RequestMapping("/ub")
public class UserBooksController {
	protected static String className = UserBooksController.class.getName();
	protected static Log logger = LogFactory.getLog(className);//日志对象
	protected static final double onePenalty= 0.1;//每天罚款一毛钱
	
	@Autowired
	BooksInfoDAO booksInfoDAO;
	@Autowired
	BooksCaseDAO booksCaseDAO;
	@Autowired
	BooksClassfyDAO booksClassfyDAO;
	@Autowired
	RolesInfoDAO rolesInfoDAO;
	@Autowired
	BorrowsInfoDAO borrowsInfoDAO;
	@Autowired
	UsersInfoService usersInfoService;
	@Autowired
	BooksPenaltyDAO booksPenaltyDAO;
	/**
	 * 进入未还书籍首页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>index<|><|><|>");
		List<BooksCase> caseList = booksCaseDAO.selectByExample(null);
		
		BooksClassfyExample example = new BooksClassfyExample();
		example.createCriteria().andTypeEqualTo((byte)2);
		List<BooksClassfy> classfyList = booksClassfyDAO.selectByExample(example);
				
		model.addAttribute("caseList", JsonUtils.jsonFromObject(caseList));
		model.addAttribute("classfyList", JsonUtils.jsonFromObject(classfyList));
		return "/b/ubIndex";
	}
	
	/**
	 * 全部借书历史
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/allPersonIndex")
	public String allPersonIndex(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>index<|><|><|>");
		List<BooksCase> caseList = booksCaseDAO.selectByExample(null);
		
		BooksClassfyExample example = new BooksClassfyExample();
		example.createCriteria().andTypeEqualTo((byte)2);
		List<BooksClassfy> classfyList = booksClassfyDAO.selectByExample(example);
		
		model.addAttribute("caseList", JsonUtils.jsonFromObject(caseList));
		model.addAttribute("classfyList", JsonUtils.jsonFromObject(classfyList));
		return "/b/allPersonIndex";
	}
	
	/**
	 * 借书历史
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/allIndex")
	public String allIndex(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>index<|><|><|>");
		List<BooksCase> caseList = booksCaseDAO.selectByExample(null);
		
		BooksClassfyExample example = new BooksClassfyExample();
		example.createCriteria().andTypeEqualTo((byte)2);
		List<BooksClassfy> classfyList = booksClassfyDAO.selectByExample(example);
		
		model.addAttribute("caseList", JsonUtils.jsonFromObject(caseList));
		model.addAttribute("classfyList", JsonUtils.jsonFromObject(classfyList));
		return "/b/allIndex";
	}
	
	/**
	 * 获取书籍列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getBorrows")
	public @ResponseBody String getBorrows(HttpServletRequest request,HttpServletResponse response){
		logger.info("<|>"+className+"<|>getBooks<|><|><|>");
		int pageNo = RequestUtils.getInt(request, "page", 1);
		int pageSize = RequestUtils.getInt(request, "pagesize", 0);
		int isBack = RequestUtils.getInt(request, "isBack", -1);
		int allPerson = RequestUtils.getInt(request, "allP", 0);
		
		
		
		BorrowsInfoExample example = new BorrowsInfoExample();
		BorrowsInfoExample.Criteria c = null;
		UsersInfo user = null;
		if(-1 != isBack){
			if(null == c){
				c= example.createCriteria();
			}
			c.andIsbackEqualTo(isBack);
		}
		if(allPerson == 0){
			if(null == c){
				c= example.createCriteria();
			}
			user = ServletUtils.getLgUser(request);
			c.andBorrowerEqualTo(user.getId());
		}
		
		
		example.setOrderByClause(" borrowTime desc ");
		
		List<BorrowsInfo> list = borrowsInfoDAO.selectByExample(example);
		List<Map<String,Object>> resultList = new LinkedList<Map<String,Object>>();
		
		for(BorrowsInfo info : list){
			BooksInfo book = this.booksInfoDAO.selectByPrimaryKey(info.getBookid());
			Map<String,Object> temp = new HashMap<String,Object>();
			temp.put("id", book.getId());
			temp.put("classfyid", book.getClassfyid());
			temp.put("language", book.getLanguage());
			temp.put("caseid", book.getCaseid());
			temp.put("bookname", book.getBookname());
			temp.put("borrowTime", info.getBorrowtime());
			temp.put("isBack", info.getIsback());
			temp.put("planTime", info.getPlantime());
			temp.put("isContinue", info.getIscontinue());
			temp.put("backTime", info.getBacktime());
			temp.put("ispenalty", info.getIspenalty());
			if(info.getIspenalty() != null && info.getIspenalty().equals(true) && user != null){
				BooksPenaltyExample enaltyExample = new BooksPenaltyExample();
				enaltyExample.createCriteria().andBookidEqualTo(book.getId()).andBorrowerEqualTo(user.getId());
				BooksPenalty penalty;
				try {
					penalty = this.booksPenaltyDAO.selectByExample(
							enaltyExample).get(0);
					temp.put("money", penalty.getPenaltyamount()+"元");
					temp.put("reasonType", penalty.getReasontype());
				} catch (Exception e) {
				}
			}
			resultList.add(temp);
		}
		
		int count = borrowsInfoDAO.selectCountByExample(example);
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("Rows", resultList);
		result.put("Total", count);
		return JsonUtils.jsonFromObject(result);
	}
	
	
	@RequestMapping("/continueBorrows/{bookId}")
	public @ResponseBody String continueBorrows(HttpServletRequest request,
			HttpServletResponse response,@PathVariable Integer bookId){
		logger.info("<|>"+className+"<|>continueBorrows<|><|><|>");
		UsersInfo user = ServletUtils.getLgUser(request);
		BorrowsInfoExample example = new BorrowsInfoExample();
		BorrowsInfoExample.Criteria c = example.createCriteria();
		c.andBorrowerEqualTo(user.getId());
		c.andBookidEqualTo(bookId);
		BorrowsInfo info = null;
		try {
			info = this.borrowsInfoDAO.selectByExample(example).get(0);
		} catch (Exception e) {
		}
		if(info == null){
			return "没有找到要续借的书籍!";
		}
		Integer continued = 1;
		if(continued.equals(info.getIscontinue())){
			return "书籍已经续借过了!";
		}
		info.setIscontinue(1);
		Date date = info.getPlantime();
		date.setDate(date.getDate()+30);
		info.setPlantime(date);
		if(this.borrowsInfoDAO.updateByPrimaryKeySelective(info)>0){
			return "续借成功!";
		}else{
			return "系统错误,续借失败!";
		}
	}
	
	@RequestMapping("/getBacksInfo/{bookId}")
	public @ResponseBody String getBacksInfo(HttpServletRequest request,
			HttpServletResponse response,@PathVariable Integer bookId){
		logger.info("<|>"+className+"<|>getBacksInfo<|><|><|>");
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		
		
		BorrowsInfoExample example = new BorrowsInfoExample();
		BorrowsInfoExample.Criteria c = example.createCriteria();
		c.andIsbackEqualTo(0);
		c.andBookidEqualTo(bookId);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		BorrowsInfo info = null;
		try {
			info = this.borrowsInfoDAO.selectByExample(example).get(0);
		} catch (Exception e) {
		}
		
		if(info == null){
			resultMap.put("msg", "没有找到要还的书籍!");
			return JsonUtils.jsonFromObject(resultMap);
		}
		

		UsersInfo user = this.usersInfoService.getById(info.getBorrower());
		resultMap.put("user", user);
		resultMap.put("book", this.booksInfoDAO.selectByPrimaryKey(info.getBookid()));
		resultMap.put("borrow", info);
		
		Date nowDate = new Date();
		long today = nowDate.getTime();
		
		long planTime = info.getPlantime().getTime();
		if(today > planTime){
			info.setIspenalty(1);
			BooksPenalty penalty  = new BooksPenalty();
			penalty.setBookid(bookId);
			penalty.setBorrower(user.getId());
			long daysLong = (today-planTime)/86400000;
			int day= Math.round(daysLong);
			penalty.setOverdueday(day);
			penalty.setReasontype(1);
			penalty.setPenaltyamount(day*onePenalty);
			resultMap.put("penalty", penalty);
		}
		
		return JsonUtils.jsonFromObject(resultMap);
	}
	
	@RequestMapping("/saveBackBook/{bookId}")
	public @ResponseBody String saveBackBook(HttpServletRequest request,HttpServletResponse response,@PathVariable Integer bookId){
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		
		BorrowsInfoExample example = new BorrowsInfoExample();
		BorrowsInfoExample.Criteria c = example.createCriteria();
		c.andIsbackEqualTo(0);
		c.andBookidEqualTo(bookId);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		BorrowsInfo info = null;
		try {
			info = this.borrowsInfoDAO.selectByExample(example).get(0);
		} catch (Exception e) {
		}
		
		if(info == null){
			resultMap.put("error", "-1");
			resultMap.put("msg", "没有找到要还的书籍!");
			return JsonUtils.jsonFromObject(resultMap);
		}
		UsersInfo user = this.usersInfoService.getById(info.getBorrower());
		
		int reasonType = RequestUtils.getInt(request, "reasonType",0);
		BooksInfo book = this.booksInfoDAO.selectByPrimaryKey(info.getBookid());
		double penaltyamount = RequestUtils.getDouble(request, "penaltyamount",0);
		
		if(reasonType > 0 && penaltyamount > 0){
			BooksPenalty penalty = new BooksPenalty();
			penalty.setOperator(lgUser.getId());
			penalty.setTime(new Date());
			penalty.setBookid(book.getId());
			penalty.setBorrower(user.getId());
			penalty.setReasontype(reasonType);
			penalty.setPenaltyamount(penaltyamount);
			booksPenaltyDAO.insert(penalty);
			info.setIspenalty(1);
		}else{
			info.setIspenalty(0);
		}
		
		book.setValid(0);
		this.booksInfoDAO.updateByPrimaryKeySelective(book);
		
		info.setBacktime(new Date());
		info.setIsback(1);
		info.setBackoperator(lgUser.getId());
		
		this.borrowsInfoDAO.updateByPrimaryKeySelective(info);
		resultMap.put("success", "success");
		return JsonUtils.jsonFromObject(resultMap);
	}
	
		
	
}
